const Router = require('koa-router');
const requireDirectory = require('require-directory')

class InitManager {
    static initCore(app) {
        InitManager.app = app
        InitManager.initLoaRouter()
        InitManager.LoadHttpException()
        InitManager.loadConfig()
    }
    // 加载全部路由
    static initLoaRouter() {
        // 绝对路径
        const apiDirectory = `${process.cwd()}/app/api`
        // 路由自动加载
        requireDirectory(module, apiDirectory, {
            visit: whenLoadModule
        })

        function whenLoadModule(obj) {
            if (obj instanceof Router) {
                InitManager.app.use(obj.routes())
            }
        }
    }

    static loadConfig(path = '') {
        const configPath = path || process.cwd() + '/config/config.js'
        const config = require(configPath)
        global.config = config
    }

    static LoadHttpException() {
        const errors = require('./http-exception')
        global.errs = errors
    }
}

module.exports = InitManager